#! /usr/bin/python

# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="MrEction"
__date__ ="$Apr 12, 2011 7:22:07 PM$"

import pygame
from hexconfig import *
#import datahandler

REPLAY = "04121652"
#REPLAY_LIST = ["petesshortreplays/04282359", "petesshortreplays/04290000", "petesshortreplays/04290001", "petesshortreplays/04290002", "petesshortreplays/04290003","petesshortreplays/0429000538", "petesshortreplays/0429000600", "petesshortreplays/0429000620", "petesshortreplays/0429000636", "petesshortreplays/0429000723", "petesshortreplays/0429000737", "petesshortreplays/0429000823", "petesshortreplays/0429000849", "petesshortreplays/0429000910"]
REPLAY_LIST=[]
REPLAY_LIST.extend(["newreplays/04261738","newreplays/04261742","newreplays/04261759","newreplays/04261805","newreplays/04261822", "newreplays/04261847", "newreplays/04261855", "newreplays/04261906"])
REPLAY_LIST.extend(["newerreplays/04281222","newerreplays/04282005","newerreplays/04282015","newerreplays/05010453","newerreplays/05010507","newerreplays/05010514","newerreplays/05010523","newerreplays/05010528","newerreplays/05010532"])
REPLAY_LIST.extend(["goodreplays/04070202","goodreplays/04070205","goodreplays/04070228","goodreplays/04070311","goodreplays/04070543","goodreplays/04121731","goodreplays/04121743","goodreplays/04122038"])
REPLAY_LIST.extend(["goodreplays/04131831","goodreplays/04132052","goodreplays/04161520","goodreplays/04161930","goodreplays/04161944","goodreplays/04161947","goodreplays/04161957","goodreplays/04252226"])
REPLAY_LIST.extend(["05021743", "05040427", "05040429", "05040432", "05040435", "05040437", "05040442"])
#REPLAY_LIST = ["05042151","05042157","05042207", "05042209", "05042221", "05042235", "05042236", "05042247","05042247","05050238","05050439" ]
#REPLAY_LIST.extend(["05050444","05050449", "05050453", "05051043", "05051112", "05051113", "05051349", "05051512", "05051534", "05060436", "05060437"])
pygame.init()

SAVE_DATA = True

LOAD_DATA = True
ADD_REPLAYS = True
SPREAD_REPLAYS = True
FLESH_OUT_REPLAYS = False

PROPOGATE_UTILITY = True

MERGE_DATA_SET = True

PRINT_DATA_SET = False

if __name__ == "__main__":
    print "Train with Replays"
    clock = pygame.time.Clock()
    clock.tick()
    screen = pygame.display.set_mode((SWIDTH,SHEIGHT))#,pygame.FULLSCREEN)#,pygame.HWSURFACE)

    dh = DataHandler()
    
    ds = DataSet()
    #dh.autoSaveDataSet(ds)
    #exit()
    if LOAD_DATA:
        originalDS = dh.autoLoadDataSet()#
        """print "UTIL PROPOGATION PRINTOUTS:"
        numWithUtil = 0
        keys = originalDS.nodes.keys()
        for k in keys:
            if not originalDS.nodes[k].util()==0.0:
                numWithUtil+=1
                #print ds.nodes[k].util(), ds.nodes[k].stateString(), ds.nodes[k].w
        print "  ", numWithUtil, "/", len(keys), "nodes have utility"
        """
        

        totalwithutil = 0
        """for n in originalDS.nodes:
            #print originalDS.getNode(n)
            if originalDS.getNode(n).util() != 0.0: totalwithutil += 1
        print "Total w/ with utility:", totalwithutil"""
    #endBoardStates = [[] for i in range(2)]
    propogationList = []
    if ADD_REPLAYS:
        for r in REPLAY_LIST:
            replay = loadReplay(r)
            currentState = replay.setups
            endBoardStates = [[] for i in range(2)]
            turn = 0
            for e in replay.moveList:
                #print "adding move"

                nextState = stateStringFromActionList(currentState,e)
                endBoardStates[turn].append(nextState)

                if nextState[0] == "W":
                    propogationList.append((endBoardStates[turn][:-1], 1.0))
                    propogationList.append((endBoardStates[1 if turn == 0 else 0][-5:], -1.0))
                    ds.addEdge(currentState, nextState, e)
                    currentState = nextState
                    break
                unitTeam = teamKilledByActionList(currentState,e)
                if unitTeam==0:
                    propogationList.append((endBoardStates[turn][-2:], -.7))
                    propogationList.append((endBoardStates[1 if turn == 0 else 0][-4:],  .5))
                elif unitTeam==1:
                    propogationList.append((endBoardStates[turn][-4:],  .5))
                    propogationList.append((endBoardStates[1 if turn == 0 else 0][-3:], -.75))

                ds.addEdge(currentState, nextState, e)
                currentState = nextState
                    

               
                #print "added edge", currentState, nextState


                #print currentState
                #p0units, p1units, p0king, p1king = stateStringToBoard(currentState, turn)
                currentState = switchStateStringToOtherTeam(currentState, turn)
                turn = (turn+1)%2

                #currentState = boardToStateString(p0units, p1units, p0king, p1king, turn)
                #print currentState
            print "end: ", endBoardStates
        ms = clock.tick()
        secs = ms/1000
        mins = secs/60
        print
        print "TIME TO ADD DATA:",mins,"mins,",secs%60 if secs>60 else secs,"secs"
        print "NODES_LENGTH",len(ds.nodes)
        print "EDGES_LENGTH",len(ds.edges)
        #if SAVE_DATA: dh.autoSaveDataSet(ds)

    if SPREAD_REPLAYS:
        print "spreading replays"
        loadedreplaylist = []
        """for r in REPLAY_LIST:
            loadedreplaylist.append(loadReplay("newsreplays/"+r))
        ds.spreadDataSet(loadedreplaylist, 0)"""
        keys = ds.nodes.keys()
        for key in keys:
            #print ds.nodes[key]
            ds.spreadStateString(key, 0)

        ms = clock.tick()
        secs = ms/1000
        mins = secs/60
        print
        print "TIME TO SPREAD DATA:",mins,"mins,",secs%60 if secs>60 else secs,"secs"
        print "NODES_LENGTH",len(ds.nodes)
        print "EDGES_LENGTH",len(ds.edges)
        #if SAVE_DATA: dh.autoSaveDataSet(ds)





    if MERGE_DATA_SET:
        clock.tick()
        originalDS.addDSToDataSet(ds)
        ds = originalDS
        
        ms = clock.tick()
        secs = ms/1000
        mins = secs/60
        print
        print "TIME TO MERGE DATA:",mins,"mins,",secs%60 if secs>60 else secs,"secs"
        print "NODES_LENGTH",len(ds.nodes)
        print "EDGES_LENGTH",len(ds.edges)
        if SAVE_DATA: dh.autoSaveDataSet(ds)

    if FLESH_OUT_REPLAYS:
        ds.fleshOutEdges()

        ms = clock.tick()
        secs = ms/1000
        mins = secs/60
        print
        print "TIME TO FLESH OUT DATA:",mins,"mins,",secs%60 if secs>60 else secs,"secs"
        print "NODES_LENGTH",len(ds.nodes)
        print "EDGES_LENGTH",len(ds.edges)

        #if SAVE_DATA: dh.autoSaveDataSet(ds)

    if PROPOGATE_UTILITY:
        clock.tick()
        for prop in propogationList:
            ds.propogateUtil(prop[0], prop[1])

        for i in range(len(endBoardStates)):
            if i == 0:
                continue
            for endStateString in endBoardStates[i]:
                print endStateString
                node = ds.getNode(endStateString)
                node.addUtil((node.util()+0.1)*node.w,0.1)
        
        ms = clock.tick()
        secs = ms/1000
        mins = secs/60
        print
        print "TIME TO PROPOGATE UTIL: ",mins,"mins,",secs%60 if secs>60 else secs,"secs"
        print "NODES_LENGTH",len(ds.nodes)
        print "EDGES_LENGTH",len(ds.edges)

        print "UTIL PROPOGATION PRINTOUTS:"
        numWithUtil = 0
        keys = ds.nodes.keys()
        for k in keys:
            if not ds.nodes[k].util()==0.0:
                numWithUtil+=1
                #print ds.nodes[k].util(), ds.nodes[k].stateString(), ds.nodes[k].w
        print "  ", numWithUtil, "/", len(keys), "nodes have utility"
       
        if SAVE_DATA: dh.autoSaveDataSet(ds)
        

